package org.mspring.mlog.web.module.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.service.search.NewsSearchService;
import org.mspring.mlog.service.search.PostSearchService;
import org.mspring.mlog.service.search.impl.HibernateSearchTemplate;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 
 * @author Gao Youbo
 * @since 2013年7月5日
 */
@Widget
@RequestMapping("/search")
public class Web_SearchWidget extends Web_AbstractWidget {

    @Autowired
    private PostSearchService postSearchService;
    @Autowired
    private NewsSearchService newsSearchService;
    @Autowired
    private HibernateSearchTemplate hibernateSearchTemplate;

    @SuppressWarnings({ "rawtypes" })
    @RequestMapping({ "/", "" })
    public String search(@ModelAttribute Page page, @RequestParam(required = false) String w, @RequestParam(required = false) String scope, HttpServletRequest request, HttpServletResponse response, Model model) {
        String[] fields = new String[] { "title", "summary", "content", "catalog.name" };
        if (StringUtils.isNotBlank(w)) {
            w = StringUtils.encoding(w, "ISO-8859-1", "UTF-8").trim();
            if ("post".equals(scope)) {
                page = postSearchService.listPage(page, w, fields);
            } else {
                page = newsSearchService.listPage(page, w, fields);
            }
        }
        model.addAttribute("page", page);
        model.addAttribute("w", w);
        model.addAttribute("scope", scope);
        return "skin:/search/" + (scope == null ? "news" : scope);
    }
}
